/********************************************************************************
Copyright (C), TianNeng Power. Ltd.
Author: 	hxbao
Version: 	V0.0
Date: 		2020/10/16
History:
	V0.0		2021/9/16		 Preliminary
********************************************************************************/
#include "includes.h"
#include "SEGGER_RTT.h"

static void Bsp_Init(void)
{

	GPIOInit();
	TWI_Init();
	bsp_InitTimer();
}


void main(void)
{
	uint16_t newCrc;
	uint8_t count = 5;

	SEGGER_RTT_Init();
	SEGGER_RTT_printf(0, "App start\n");
	//中断地址偏移设置
	MCU_SetNVOffset();
	Clk_Config();
	SysTick_Config(SystemCoreClock / 1000);
	
	//中断优先级最高
	//NVIC_SetPriority (SysTick_IRQn, 0);

	//时钟校准，需要生产测试阶段PF0，输入标准24M 时钟源
	//RCH_Calbration();
#if(MCU_LIB_SELECT ==1)
	while (Ok != Flash_Init(6, TRUE))//TRUE-深度休眠低功耗 FALSE-深度休眠不进入低功耗
	{
		count--;
		if (count == 0)
		{
			break;
		}
	}
#elif(MCU_LIB_SELECT ==2)
	//DBG_ConfigPeriph(DBG_STOP|DBG_IWDG_STOP, ENABLE);	
	DBG_ConfigPeriph(DBG_STOP|DBG_IWDG_STOP, DISABLE);	
#endif
	Flash_Read(APP_CONFIG_CRC_ADDR, (uint8_t *)&newCrc, 2);	
	
	//new fw version crc check
	SEGGER_RTT_printf(0, "new crc:%x\n", newCrc);
	SEGGER_RTT_printf(0, "SystemCoreClockFreq:%d\n", SystemCoreClock);
	SEGGER_RTT_printf(0, "version:%s\n", TN_FW_VER);
	SEGGER_RTT_printf(0, "complie time:%s\n", COMPLIE_TIME);

   
	Bsp_Init();
	NiuLogicInit();

	//开启watchdog
	Iwdt_Config();
	Iwdt_Start();



	while(1)
	{
#if(MCU_LIB_SELECT ==1)
	//时钟监控,发现时钟初始化4M的情况
	 uint32_t fval;
     fval = Sysctrl_GetHClkFreq();
	 if(fval != 24000000)
	 {
		 Clk_Config();
	 }
#endif		
		NiuLogicRun();	
		//喂狗
		Iwdt_Feed();

#ifdef UNIT_TEST_EN
		UnitTestProcess();
#endif
	}
}
